﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Data.OracleClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Runtime.Remoting;
using System.Collections;
using Srvtools;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace EEPClientDBSocket
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private String Status;
        private String oldSocketName;
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Show();
            this.ShowInTaskbar = true;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
        }

        private void TSclose_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void TShide_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        String[] OptionMessage;
        private void frmMain_Load(object sender, EventArgs e)
        {
            RemoveFormText();
            this.Text += "(Stop)";
            TSactive.Checked = false;
            TSstop.Checked = true;

            this.Hide();
            this.ShowInTaskbar = false;
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;

            LoadData();

            String ss;
            ss = Application.StartupPath + "\\";
            RemotingConfiguration.Configure(ss + "EEPClientDBSocket.exe.config", true);

            OptionMessage = getOption();
            if (Convert.ToBoolean(OptionMessage[5])) TSactive_Click(sender, e);
            isRegister = Register(false, OptionMessage[0]);
            if (OptionMessage[6] != "")
                this.timer1.Interval = 50000;
            else if (Convert.ToInt32(OptionMessage[3]) != 0)
                this.timer1.Interval = Convert.ToInt32(OptionMessage[3]) * 1000;

            this.Hide();
            this.ShowInTaskbar = false;
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            this.Select();

            if (isRegister)
            {
                object[] myRet1 = CliUtils.CallMethod("GLModule", "GetDB", null);
                if (myRet1[1] != null && myRet1[1] is ArrayList)
                {
                    ArrayList dbList = (ArrayList)myRet1[1];
                    foreach (String db in dbList)
                    {
                        this.cbDataBase.Items.Add(db);
                    }
                }

                DataSet dsSolution = new DataSet();
                object[] myRet2 = CliUtils.CallMethod("GLModule", "GetSolution", null);
                if ((null != myRet2) && (0 == (int)myRet2[0]))
                    dsSolution = ((DataSet)myRet2[1]);

                for (int i = 0; i < dsSolution.Tables[0].Rows.Count; i++)
                    this.cbSolution.Items.Add(dsSolution.Tables[0].Rows[i]["itemtype"].ToString());

                if (OptionMessage[7].ToLower() == "true")
                {
                    object[] ServerDateTime = CliUtils.CallMethod("GLModule", "GetServerTime", null);
                    if (ServerDateTime[0] != null && ServerDateTime[0].ToString() == "0")
                    {
                        SetTime(ServerDateTime[1].ToString(), ServerDateTime[2].ToString());
                    }
                }
            }

            SetEnableOff();
            if (this.lbSocket.SelectedItem != null)
            {
                FillData(this.lbSocket.SelectedItem.ToString());
            }
        }

        private void LoadData()
        {
            this.lbSocket.Items.Clear();
            String s = Application.StartupPath + "\\EEPClientDBSocket.xml";
            if (File.Exists(s))
            {
                XmlDocument DBXML = new XmlDocument();
                FileStream aFileStream = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.None);
                DBXML.Load(aFileStream);
                XmlNode aNode = DBXML.DocumentElement.FirstChild;
                lbSocket.BeginUpdate();
                try
                {
                    lbSocket.Items.Clear();
                    while (aNode != null)
                    {
                        lbSocket.Items.Add(aNode.Attributes["SocketName"].Value);
                        aNode = aNode.NextSibling;
                    }
                }
                finally
                {
                    lbSocket.EndUpdate();
                    aFileStream.Close();
                }
            }
        }

        private String[] getOption()
        {
            String s = Application.StartupPath + "\\EEPClientDBSocketOptions.xml";
            String[] option = new String[8];

            if (File.Exists(s))
            {
                XmlDocument DBXML = new XmlDocument();
                FileStream aFileStream = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.None);
                DBXML.Load(aFileStream);
                XmlNode aNode = DBXML.DocumentElement.FirstChild;
                if (aNode.Attributes["ServerIP"] == null || aNode.Attributes["ServerIP"].Value == "")
                {
                    String cpath;
                    cpath = Application.StartupPath + "\\";

                    XmlDocument xmlDocC = new XmlDocument();
                    xmlDocC.Load(cpath + "EEPClientDBSocket.exe.config");

                    if (xmlDocC != null && xmlDocC.FirstChild != null)
                    {
                        XmlNode n = xmlDocC.FirstChild.FirstChild.FirstChild.FirstChild.
                            SelectSingleNode("wellknown[@type='Srvtools.LoginService, Srvtools']");
                        if (n != null)
                        {
                            string url = n.Attributes["url"].InnerText;

                            MatchCollection mc = Regex.Matches(url, @"(\S+):");
                            string[] ip = mc[0].ToString().Split("/,:".ToCharArray());
                            option[0] = ip[3];
                        }
                    }
                }
                else
                    option[0] = aNode.Attributes["ServerIP"].Value;
                option[1] = aNode.Attributes["UserID"].Value;
                option[2] = aNode.Attributes["Password"].Value;
                option[3] = aNode.Attributes["Timer"].Value;
                option[4] = aNode.Attributes["TimeOut"].Value;
                option[5] = aNode.Attributes["StartActive"].Value;
                option[6] = aNode.Attributes["SocketTime"].Value;
                option[7] = aNode.Attributes["SynchroLocalTime"].Value;
                aFileStream.Close();
            }

            return option;
        }

        private void Log(String SocketName, String Date, String Action, String ProviderName, String TableName, String RunStatus)
        {
            string s = Application.StartupPath + "\\EEPClientDBSocket.txt";

            FileStream file;
            if (!File.Exists(s))
            {
                file = new FileStream(s, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
                file.Close();
            }

            ArrayList alLog = new ArrayList();
            StreamReader sreader = new StreamReader(s);
            alLog.Add(sreader.ReadToEnd());
            sreader.Close();
            alLog.Add("SocketName: " + SocketName);
            alLog.Add("Date/Time: " + Date);
            alLog.Add("Action: " + Action);
            alLog.Add("ProviderName: " + ProviderName);
            alLog.Add("TableName: " + TableName);
            alLog.Add("Status: " + RunStatus);
            StreamWriter swriter = new StreamWriter(s);
            for (int i = 0; i < alLog.Count; i++)
                swriter.WriteLine(alLog[i]);
            swriter.Close();
        }

        private bool isRegister = false;
        private bool Register(bool showmessage, string IP)
        {
            if (IP != "")
            {
                CliUtils.fRemoteIP = IP;
            }
            string message = "";
            bool rtn = CliUtils.Register(ref message);
            if (rtn)
            {
                CliUtils.GetSysXml(Application.StartupPath + @"\sysmsg.xml");
            }
            else
            {
                if (showmessage)
                {
                    MessageBox.Show(message);
                }
            }
            return rtn;
        }

        private void RemoveFormText()
        {
            if (this.Text.Contains("("))
            {
                this.Text = this.Text.Remove(this.Text.IndexOf('('));
            }
        }

        private void frmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
                this.Hide();
        }

        private void TSsetting_Click(object sender, EventArgs e)
        {
            this.Show();
            this.ShowInTaskbar = true;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
        }

        private void btnPN_Click(object sender, EventArgs e)
        {
            frmProviderName fpn = new frmProviderName(this.cbSolution.Text);
            fpn.ShowDialog();
            this.tbProviderName.Text = fpn.Module + "." + fpn.DBCommand;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DoSave();
        }

        private void DoSave()
        {
            String SocketName = this.tbSocketName.Text;
            String isActive = this.cbActive.Checked.ToString();
            //String ServerIP = this.tbServerIP.Text;
            //String Port = this.tbPort.Text;
            //String UserID = this.tbUserID.Text;
            //String Password = this.tbPassword.Text;
            String Solution = this.cbSolution.Text;
            String DataBase = this.cbDataBase.Text;
            String ProviderName = this.tbProviderName.Text;
            String WhereString = this.tbWhereString.Text;
            String ConnString = this.tbConnString.Text;
            String ConnType = this.cbConnType.Text;
            String OperateMode = this.cbOpMode.Text;
            String LocalTable = this.tbLocalTable.Text;
            String Field = this.tbField.Text;
            String Mode = this.cbMode.Text;

            if (this.labelField.Text == "FlagField" && this.tbField.Text.Split(';').Length > 1)
            {
                MessageBox.Show("Flag Field is ONLY able to contain one column.");
                return;
            }
                
            String s = Application.StartupPath + "\\EEPClientDBSocket.xml";
            XmlDocument DBXML = new XmlDocument();
            FileStream aFileStream;
            if (!File.Exists(s))
            {
                try
                {
                    aFileStream = new FileStream(s, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
                    try
                    {
                        XmlTextWriter w = new XmlTextWriter(aFileStream, new System.Text.ASCIIEncoding());
                        w.Formatting = Formatting.Indented;
                        w.WriteStartElement("InfolightEEPClientDBSocket");
                        w.WriteEndElement();
                        w.Close();
                    }
                    finally
                    {
                        aFileStream.Close();
                    }
                }
                catch (Exception er) { string str = er.Message; }
            }

            try
            {
                aFileStream = new FileStream(s, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                try
                {
                    DBXML.Load(aFileStream);
                    XmlNode aNode = null;

                    String newSocketName = SocketName;
                    if (Status == "modify")
                        SocketName = oldSocketName;
                    for (int j = DBXML.DocumentElement.ChildNodes.Count - 1; j >= 0; j--)
                        if (DBXML.DocumentElement.ChildNodes[j].Attributes["SocketName"].Value.Trim().ToUpper().Equals(SocketName.ToUpper()))
                        {
                            aNode = DBXML.DocumentElement.ChildNodes[j];
                            break;
                        }

                    if (aNode == null)
                    {
                        XmlElement elem = DBXML.CreateElement("String");
                        XmlAttribute attr = DBXML.CreateAttribute("SocketName");
                        attr.Value = newSocketName;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("isActive");
                        attr.Value = isActive;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("Solution");
                        attr.Value = Solution;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("DataBase");
                        attr.Value = DataBase;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("ProviderName");
                        attr.Value = ProviderName;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("WhereString");
                        attr.Value = WhereString;
                        elem.Attributes.Append(attr);
                        
                        attr = DBXML.CreateAttribute("ConnString");
                        attr.Value = ConnString;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("ConnType");
                        attr.Value = ConnType;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("OperateMode");
                        attr.Value = OperateMode;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("LocalTable");
                        attr.Value = LocalTable;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("Field");
                        attr.Value = Field;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("Mode");
                        attr.Value = Mode;
                        elem.Attributes.Append(attr);

                        DBXML.DocumentElement.AppendChild(elem);
                    }
                    else
                    {
                        aNode.Attributes["SocketName"].InnerText = newSocketName;
                        aNode.Attributes["isActive"].InnerText = isActive;
                        aNode.Attributes["Solution"].InnerText = Solution;
                        aNode.Attributes["DataBase"].InnerText = DataBase;
                        aNode.Attributes["ProviderName"].InnerText = ProviderName;
                        aNode.Attributes["WhereString"].InnerText = WhereString;
                        aNode.Attributes["ConnString"].InnerText = ConnString;
                        aNode.Attributes["ConnType"].InnerText = ConnType;
                        aNode.Attributes["OperateMode"].InnerText = OperateMode;
                        aNode.Attributes["LocalTable"].InnerText = LocalTable;
                        aNode.Attributes["Field"].InnerText = Field;
                        aNode.Attributes["Mode"].InnerText = Mode;
                    }
                }
                finally
                {
                    aFileStream.Close();
                }
                DBXML.Save(s);
            }
            catch (Exception er) { string str = er.Message; }

            MessageBox.Show("Save succeed!");
            SetEnableOff();
            LoadData();
        }

        private void cbOpMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbOpMode.SelectedIndex == 0)
            {
                this.labelField.Text = "KeyFiels";
                this.tbField.Text = "";
                this.cbMode.Text = "";
                this.cbMode.Items.Clear();
                this.cbMode.Items.Add("Insert");
                this.cbMode.Items.Add("Update");
            }
            else if (this.cbOpMode.SelectedIndex == 1)
            {
                this.labelField.Text = "FlagField";
                this.tbField.Text = "";
                this.cbMode.Text = "";
                this.cbMode.Items.Clear();
                this.cbMode.Items.Add("Copy");
                this.cbMode.Items.Add("Append");
                this.cbMode.Items.Add("Append & Drop");
            }
        }

        private void SetEnableOff()
        {
            this.tbSocketName.Enabled = false;
            this.cbActive.Enabled = false;
            //this.tbServerIP.Enabled = false;
            //this.tbPort.Enabled = false;
            //this.tbUserID.Enabled = false;
            //this.tbPassword.Enabled = false;
            this.cbSolution.Enabled = false;
            this.cbDataBase.Enabled = false;
            this.tbProviderName.Enabled = false;
            this.tbWhereString.Enabled = false;
            this.tbConnString.Enabled = false;
            this.cbConnType.Enabled = false;
            this.cbOpMode.Enabled = false;
            this.tbLocalTable.Enabled = false;
            this.tbField.Enabled = false;
            this.btnFields.Enabled = false;
            this.cbMode.Enabled = false;
            this.btnPN.Enabled = false;
            this.btnLocalTable.Enabled = false;
            this.btnSave.Enabled = false;
            this.TSMainSave.Enabled = false;
            this.btnCancel.Enabled = false;
        }

        private void SetEnableOn()
        {
            this.tbSocketName.Enabled = true;
            this.cbActive.Enabled = true;
            //this.tbServerIP.Enabled = true;
            //this.tbPort.Enabled = true;
            //this.tbUserID.Enabled = true;
            //this.tbPassword.Enabled = true;
            this.cbSolution.Enabled = true;
            this.cbDataBase.Enabled = true;
            this.tbProviderName.Enabled = true;
            this.tbWhereString.Enabled = true;
            this.tbConnString.Enabled = true;
            this.cbConnType.Enabled = true;
            this.cbOpMode.Enabled = true;
            this.tbLocalTable.Enabled = true;
            this.tbField.Enabled = true;
            this.btnFields.Enabled = true;
            this.cbMode.Enabled = true;
            this.btnPN.Enabled = true;
            this.btnLocalTable.Enabled = true;
            this.btnSave.Enabled = true;
            this.TSMainSave.Enabled = true;
            this.btnCancel.Enabled = true;
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            Status = "modify";
            oldSocketName = this.tbSocketName.Text;
            SetEnableOn();
        }

        private List<String> GetKeyFields()
        {
            List<String> fields = new List<string>();
            if (this.tbConnString.Text != null && this.tbConnString.Text != "" && this.tbLocalTable.Text != null && this.tbLocalTable.Text != "")
            {
                try
                {
                    IDbConnection conn = CreateConnection(this.cbConnType.Text, this.tbConnString.Text);
                    String sql = "select * from " + this.tbLocalTable.Text;
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    IDbCommand cmd = CreateCommand(this.cbConnType.Text, conn, sql);
                    IDataReader idr = cmd.ExecuteReader();
                    DataTable dt = idr.GetSchemaTable();
                    fields.Clear();
                    foreach (DataRow dr in dt.Rows)
                        fields.Add(dr["ColumnName"].ToString());
                    conn.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return fields;
        }

        private void FillData(String Socket)
        {
            string s = Application.StartupPath + "\\EEPClientDBSocket.xml";
            if (File.Exists(s))
            {
                XmlDocument DBXML = new XmlDocument();
                FileStream aFileStream = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.None);
                DBXML.Load(aFileStream);
                XmlNode aNode = DBXML.DocumentElement.FirstChild;
                try
                {
                    while (aNode != null)
                    {
                        if (Socket == aNode.Attributes["SocketName"].Value)
                        {
                            this.tbSocketName.Text = aNode.Attributes["SocketName"].Value;
                            this.cbActive.Checked = Convert.ToBoolean(aNode.Attributes["isActive"].Value);
                            //this.tbServerIP.Text = aNode.Attributes["ServerIP"].Value;
                            //this.tbPort.Text = aNode.Attributes["Port"].Value;
                            //this.tbUserID.Text = aNode.Attributes["UserID"].Value;
                            //this.tbPassword.Text = aNode.Attributes["Password"].Value;
                            this.cbSolution.Text = aNode.Attributes["Solution"].Value;
                            this.cbDataBase.Text = aNode.Attributes["DataBase"].Value;
                            this.tbProviderName.Text = aNode.Attributes["ProviderName"].Value;
                            this.tbWhereString.Text = aNode.Attributes["WhereString"].Value;
                            this.tbConnString.Text = aNode.Attributes["ConnString"].Value;
                            this.cbConnType.Text = aNode.Attributes["ConnType"].Value;
                            if (aNode.Attributes["OperateMode"].Value.ToLower() == "download")
                                this.cbOpMode.Text = this.cbOpMode.Items[0].ToString();
                            else if (aNode.Attributes["OperateMode"].Value.ToLower() == "upload")
                                this.cbOpMode.Text = this.cbOpMode.Items[1].ToString();
                            else
                                this.cbOpMode.Text = "";
                            this.tbLocalTable.Text = aNode.Attributes["LocalTable"].Value;
                            this.tbField.Text = aNode.Attributes["Field"].Value;
                            this.cbMode.Text = aNode.Attributes["Mode"].Value;
                        }
                        aNode = aNode.NextSibling;
                    }
                }
                finally
                {
                    aFileStream.Close();
                }
            }
        }

        private void lbSocket_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.lbSocket.SelectedItem != null)
                FillData(this.lbSocket.SelectedItem.ToString());
            else if (lbSocket.SelectedIndex == -1)
                AllClear();
        }

        private void TSMainOptions_Click(object sender, EventArgs e)
        {
            frmOption fo = new frmOption();
            fo.ShowDialog();
        }

        private void btnLocalTable_Click(object sender, EventArgs e)
        {
            if (this.tbConnString.Text != null && this.tbConnString.Text != "")
            {
                IDbConnection conn = CreateConnection(this.cbConnType.Text, this.tbConnString.Text);
                TableNameSelect tns = new TableNameSelect(conn);
                tns.ShowDialog();
                this.tbLocalTable.Text = tns.TableName;
            }
        }

        private IDbConnection CreateConnection(String connType, String connectionString)
        {
            IDbConnection conn = null;
            if (connType == "SQL")
                conn = new SqlConnection(connectionString);
            else if (connType == "Oracle")
                conn = new OracleConnection(connectionString);
            else if (connType == "OleDb")
                conn = new OleDbConnection(connectionString);
            else if (connType == "Odbc")
                conn = new OdbcConnection(connectionString);
            return conn;
        }

        private IDbCommand CreateCommand(String connType, IDbConnection conn, String sql)
        {
            IDbCommand cmd = null;
            if (connType == "SQL")
                cmd = new SqlCommand(sql, conn as SqlConnection);
            else if (connType == "Oracle")
                cmd = new OracleCommand(sql, conn as OracleConnection);
            else if (connType == "OleDb")
                cmd = new OleDbCommand(sql, conn as OleDbConnection);
            else if (connType == "Odbc")
                cmd = new OdbcCommand(sql, conn as OdbcConnection);
            return cmd;
        }

        private IDbDataAdapter CreateDataAdapter(String connType, String sql, IDbConnection conn)
        {
            IDbDataAdapter ida = null;
            if (connType == "SQL")
                ida = new SqlDataAdapter(sql, conn as SqlConnection);
            else if (connType == "Oracle")
                ida = new OracleDataAdapter(sql, conn as OracleConnection);
            else if (connType == "OleDb")
                ida = new OleDbDataAdapter(sql, conn as OleDbConnection);
            else if (connType == "Odbc")
                ida = new OdbcDataAdapter(sql, conn as OdbcConnection);
            return ida;
        }

        private void TSMainSave_Click(object sender, EventArgs e)
        {
            DoSave();
        }

        private void TSMainModify_Click(object sender, EventArgs e)
        {
            Status = "modify";
            oldSocketName = this.tbSocketName.Text;
            SetEnableOn();
        }

        private void TSMainDelete_Click(object sender, EventArgs e)
        {
            DoDelete();
        }

        private void DoDelete()
        {
            if (this.lbSocket.SelectedIndex != -1)
            {
                DialogResult dr = MessageBox.Show("Do you want to DELETE it?", "warning", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    String SocketName = lbSocket.SelectedItem.ToString();

                    XmlDocument DBXML = new XmlDocument();
                    String s = Application.StartupPath + "\\EEPClientDBSocket.xml";

                    if (File.Exists(s))
                    {
                        DBXML.Load(s);
                        XmlNode aNode = DBXML.DocumentElement.FirstChild;
                        while (aNode != null)
                        {
                            if (aNode.Attributes["SocketName"].InnerText == SocketName)
                                DBXML.DocumentElement.RemoveChild(aNode);
                            aNode = aNode.NextSibling;
                        }
                        DBXML.Save(s);
                    }
                }
                LoadData();
            }
        }

        private void TSMainNew_Click(object sender, EventArgs e)
        {
            Status = "add";
            AllClear();
            SetEnableOn();
        }

        private void AllClear()
        {
            this.tbSocketName.Text = "";
            this.cbActive.Checked = false;
            //this.tbServerIP.Text = "";
            //this.tbPort.Text = "";
            //this.tbUserID.Text = "";
            //this.tbPassword.Text = "";
            this.cbSolution.Text = "";
            this.cbDataBase.Text = "";
            this.tbProviderName.Text = "";
            this.tbWhereString.Text = "";
            this.tbConnString.Text = "";
            this.cbOpMode.Text = "";
            this.tbLocalTable.Text = "";
            this.tbField.Text = "";
            this.cbMode.Text = "";
        }

        private void TSMainWatchLog_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "\\EEPClientDBSocket.txt";
            if (!File.Exists(path))
                MessageBox.Show("Log file isn't exists!");
            else
                Process.Start("notepad.exe", path);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.lbSocket.SelectedIndex = -1;
            SetEnableOff();
        }

        private void TSactive_Click(object sender, EventArgs e)
        {
            RemoveFormText();
            this.Text += "(Active)";
            this.TSactive.Checked = true;
            this.TSstop.Checked = false;
            string s = Application.StartupPath + "\\Resources\\";
            Icon ic1 = new Icon(s + "EEPClientDBSocket16.ico");
            this.notifyIcon1.Icon = ic1;
            this.timer1.Start();
        }

        private void TSstop_Click(object sender, EventArgs e)
        {
            RemoveFormText();
            this.Text += "(Stop)";
            this.TSactive.Checked = false;
            this.TSstop.Checked = true;
            string s = Application.StartupPath + "\\Resources\\";
            Icon ic1 = new Icon(s + "EEPClientDBSocketStop16.ico");
            notifyIcon1.Icon = ic1;
            this.timer1.Stop();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            Excute(this.tbSocketName.Text,
                    this.tbWhereString.Text,
                    this.tbConnString.Text,
                    this.cbConnType.Text,
                    this.tbLocalTable.Text,
                    this.tbProviderName.Text,
                    this.tbField.Text,
                    this.cbOpMode.Text,
                    this.cbMode.Text,
                    this.cbDataBase.Text,
                    this.cbSolution.Text);
        }

        private void Excute(String socketName, String whereString, String connectionString, String connectionType, String localTableName, String providerName, String field, String opMode, String mode, String dataBase, String solution)
        {
            Login(dataBase, solution);
            InfoDataSet ids = new InfoDataSet();
            ids.RemoteName = providerName;

            String ServerTableName = "";
            IDbConnection conn;
            String sql;
            String appand;
            String insert;
            String insertColumns = "(";
            String values = "(";
            String delete;
            DataTable schema;
            ArrayList columnTypeName;
            ArrayList columnType;
            IDbDataAdapter ida;
            DataSet ds;
            bool save;
            IDbCommand cmd;
            IDbTransaction it;

            String[] fields = null;
            String deleteItem = "";

            String dateTime = "";
            String startTime = "";
            String message = "";
            String action = "";

            switch (opMode)
            {
                case "DownLoad":
                    switch (mode)
                    {
                        case "Insert":
                            try
                            {
                                startTime = DateTime.Now.ToString();
                                ids.SetWhere(whereString);
                                ids.PacketRecords = -1;
                                ids.Active = true;
                                delete = "delete " + localTableName;
                                conn = CreateConnection(connectionType, connectionString);
                                if (conn.State == ConnectionState.Closed) conn.Open();
                                it = conn.BeginTransaction();
                                cmd = CreateCommand(connectionType, conn, delete);
                                cmd.Transaction = it;
                                cmd.ExecuteNonQuery();

                                foreach (DataColumn dc in ids.RealDataSet.Tables[0].Columns)
                                    insertColumns += dc.ToString() + ", ";
                                insertColumns = insertColumns.Remove(insertColumns.LastIndexOf(','));
                                insertColumns += ")";

                                schema = getTableSchema(localTableName, connectionString, connectionType);
                                columnTypeName = new ArrayList();
                                columnType = new ArrayList();
                                foreach (DataRow dr in schema.Rows)
                                {
                                    columnTypeName.Add(dr["DataTypeName"].ToString());
                                    columnType.Add(dr["DataType"].ToString());
                                }

                                for (int i = 0; i < ids.RealDataSet.Tables[0].Rows.Count; i++)
                                {
                                    values = "(";
                                    for (int j = 0; j < ids.RealDataSet.Tables[0].Columns.Count; j++)
                                    {
                                        String value = CheckValue(ids.RealDataSet.Tables[0].Rows[i][j].ToString(), columnTypeName[j].ToString(), columnType[j].ToString());
                                        values += value + ", ";
                                    }
                                    values = values.Remove(values.LastIndexOf(','));
                                    values += ")";

                                    insert = "insert into " + localTableName + insertColumns + " values " + values;
                                    cmd = CreateCommand(connectionType, conn, insert);
                                    cmd.Transaction = it;
                                    cmd.ExecuteNonQuery();
                                }
                                it.Commit();
                            }
                            catch (Exception ex)
                            {
                                message = ex.Message;
                            }
                            dateTime = DateTime.Now.ToString();
                            action = "DownLoad - Insert";
                            message = message == "" ? ids.RealDataSet.Tables[0].Rows.Count.ToString() : message;
                            break;
                        case "Update":
                            try
                            {
                                startTime = DateTime.Now.ToString();
                                ids.SetWhere(whereString);
                                ids.PacketRecords = -1;
                                ids.Active = true;
                                conn = CreateConnection(connectionType, connectionString);
                                if (conn.State == ConnectionState.Closed) conn.Open();
                                it = conn.BeginTransaction();

                                foreach (DataColumn dc in ids.RealDataSet.Tables[0].Columns)
                                    insertColumns += dc.ToString() + ", ";
                                insertColumns = insertColumns.Remove(insertColumns.LastIndexOf(','));
                                insertColumns += ")";
                                schema = getTableSchema(localTableName, connectionString, connectionType);
                                columnTypeName = new ArrayList();
                                columnType = new ArrayList();
                                foreach (DataRow dr in schema.Rows)
                                {
                                    columnTypeName.Add(dr["DataTypeName"].ToString());
                                    columnType.Add(dr["DataType"].ToString());
                                }

                                for (int i = 0; i < ids.RealDataSet.Tables[0].Rows.Count; i++)
                                {
                                    fields = field.Split(';');
                                    deleteItem = "";
                                    foreach (String str in fields)
                                        if (str != "")
                                        {
                                            String key = ids.RealDataSet.Tables[0].Rows[i][str].ToString();
                                            deleteItem += str + "='" + key + "' and ";
                                        }
                                    deleteItem = deleteItem.Remove(deleteItem.LastIndexOf("and "));
                                    delete = "delete " + localTableName + " where " + deleteItem;
                                    cmd = CreateCommand(connectionType, conn, delete);
                                    cmd.Transaction = it;
                                    cmd.ExecuteNonQuery();

                                    values = "(";
                                    for (int j = 0; j < ids.RealDataSet.Tables[0].Columns.Count; j++)
                                    {
                                        String value = CheckValue(ids.RealDataSet.Tables[0].Rows[i][j].ToString(), columnTypeName[j].ToString(), columnType[j].ToString());
                                        values += value + ", ";
                                    }
                                    values = values.Remove(values.LastIndexOf(','));
                                    values += ")";

                                    insert = "insert into " + localTableName + insertColumns + " values " + values;
                                    cmd = CreateCommand(connectionType, conn, insert);
                                    cmd.Transaction = it;
                                    cmd.ExecuteNonQuery();
                                }
                                it.Commit();
                            }
                            catch (Exception ex)
                            {
                                message = ex.Message;
                            }
                            dateTime = DateTime.Now.ToString();
                            action = "DownLoad - Update";
                            message = message == "" ? ids.RealDataSet.Tables[0].Rows.Count.ToString() : message;
                            break;
                    }
                    break;
                case "Upload":
                    switch (mode)
                    {
                        case "Copy":
                            try
                            {
                                ids.Active = true;
                                String[] Module = providerName.Split('.');
                                ServerTableName = CliUtils.GetTableName(Module[0], Module[1], solution);
                                startTime = DateTime.Now.ToString();
                                ids.Execute("Delete " + ServerTableName);
                                ids.RealDataSet.Tables[0].Rows.Clear();
                                save = ids.ApplyUpdates(false);
                                conn = CreateConnection(connectionType, connectionString);
                                sql = "select * from " + localTableName;
                                if (conn.State == ConnectionState.Closed) conn.Open();
                                ida = CreateDataAdapter(connectionType, sql, conn);
                                ds = new DataSet();
                                ida.Fill(ds);
                                conn.Close();
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    DataRow drNew = ids.RealDataSet.Tables[0].NewRow();
                                    foreach (DataColumn dc in ds.Tables[0].Columns)
                                        drNew[dc.ToString()] = dr[dc.ToString()];
                                    ids.RealDataSet.Tables[0].Rows.Add(drNew);
                                }
                                save = ids.ApplyUpdates(false);
                            }
                            catch (Exception ex)
                            {
                                message = ex.Message;
                            }
                            dateTime = DateTime.Now.ToString();
                            action = "Upload - Copy";
                            message = message == "" ? ids.RealDataSet.Tables[0].Rows.Count.ToString() : message;
                            break;
                        case "Append":
                            try
                            {
                                startTime = DateTime.Now.ToString();
                                ids.PacketRecords = 1;
                                conn = CreateConnection(connectionType, connectionString);
                                appand = "update " + localTableName + " set " + field + "='N' where " + field + " is null";
                                if (conn.State == ConnectionState.Closed) conn.Open();
                                cmd = CreateCommand(connectionType, conn, appand);
                                it = conn.BeginTransaction();
                                cmd.Transaction = it;
                                cmd.ExecuteNonQuery();
                                it.Commit();

                                sql = "select * from " + localTableName + " where " + field + "='N'";
                                ida = CreateDataAdapter(connectionType, sql, conn);
                                ds = new DataSet();
                                ida.Fill(ds);
                                conn.Close();
                                ids.Active = true;
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    DataRow drNew = ids.RealDataSet.Tables[0].NewRow();
                                    foreach (DataColumn dc in ds.Tables[0].Columns)
                                        drNew[dc.ToString()] = dr[dc.ToString()];
                                    ids.RealDataSet.Tables[0].Rows.Add(drNew);
                                }
                                save = ids.ApplyUpdates(false);
                                appand = "update " + localTableName + " set " + field + "='Y' where " + field + "='N'";
                                if (conn.State == ConnectionState.Closed) conn.Open();
                                cmd = CreateCommand(connectionType, conn, appand);
                                it = conn.BeginTransaction();
                                cmd.Transaction = it;
                                cmd.ExecuteNonQuery();
                                it.Commit();
                            }
                            catch (Exception ex)
                            {
                                message = ex.Message;
                            }
                            dateTime = DateTime.Now.ToString();
                            action = "UpLoad - Append";
                            message = message == "" ? ids.RealDataSet.Tables[0].Rows.Count.ToString() : message;
                            break;
                        case "Append & Drop":
                            try
                            {
                                startTime = DateTime.Now.ToString();
                                ids.PacketRecords = 1;
                                conn = CreateConnection(connectionType, connectionString);
                                appand = "update " + localTableName + " set " + field + "='N' where " + field + " is null";
                                if (conn.State == ConnectionState.Closed) conn.Open();
                                cmd = CreateCommand(connectionType, conn, appand);
                                it = conn.BeginTransaction();
                                cmd.Transaction = it;
                                cmd.ExecuteNonQuery();
                                it.Commit();

                                sql = "select * from " + localTableName + " where " + field + "='N'";
                                ida = CreateDataAdapter(connectionType, sql, conn);
                                ds = new DataSet();
                                ida.Fill(ds);
                                conn.Close();
                                ids.Active = true;
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    DataRow drNew = ids.RealDataSet.Tables[0].NewRow();
                                    foreach (DataColumn dc in ds.Tables[0].Columns)
                                        drNew[dc.ToString()] = dr[dc.ToString()];
                                    ids.RealDataSet.Tables[0].Rows.Add(drNew);
                                }
                                save = ids.ApplyUpdates(false);
                                appand = "delete " + localTableName + " where " + field + "='N'";
                                if (conn.State == ConnectionState.Closed) conn.Open();
                                cmd = CreateCommand(connectionType, conn, appand);
                                it = conn.BeginTransaction();
                                cmd.Transaction = it;
                                cmd.ExecuteNonQuery();
                                it.Commit();
                            }
                            catch (Exception ex)
                            {
                                message = ex.Message;
                            }
                            dateTime = DateTime.Now.ToString();
                            action = "UpLoad - Append & Drop";
                            message = message == "" ? ids.RealDataSet.Tables[0].Rows.Count.ToString() : message;
                            break;
                    }
                    break;
            }
            SetMonitor(socketName, action, providerName, localTableName, startTime, dateTime);
            Log(socketName, dateTime, action, providerName, localTableName, message);
            LogOut();
        }

        private Char _marker = '\'';
        private String CheckValue(Object columnValue, String valueTypeName, String valueType)
        {
            if (columnValue.ToString() == "") return "null";
            bool isN = false;
            if (valueTypeName.ToLower() == "NChar".ToLower() || valueTypeName.ToLower() == "NVarChar".ToLower()
                || valueTypeName.ToLower() == "NText".ToLower() || valueTypeName.ToLower() == "NClob".ToLower())
            {
                isN = true;
            }
            if (Type.GetType(valueType).Equals(typeof(Char)) || Type.GetType(valueType).Equals(typeof(String)))
            {
                if (isN)
                    return "N" + _marker.ToString() + columnValue.ToString() + _marker.ToString();
                else
                    return _marker.ToString() + columnValue.ToString() + _marker.ToString();
            }
            else if (Type.GetType(valueType).Equals(typeof(Boolean)))
            {
                Boolean b = Convert.ToBoolean(columnValue);
                if (b)
                    return "1";
                else
                    return "0";
            }
            else if (Type.GetType(valueType).Equals(typeof(DateTime)))
            {
                DateTime t = Convert.ToDateTime(columnValue);
                string s = t.Year.ToString() + "-" + t.Month.ToString() + "-" + t.Day.ToString() + " "
                    + t.Hour.ToString() + ":" + t.Minute.ToString() + ":" + t.Second.ToString();
                return _marker.ToString() + s + _marker.ToString();
            }
            else if (Type.GetType(valueType).Equals(typeof(Byte[])))
            {
                if (columnValue.ToString().ToLower() == "system.byte[]") return "null";
                StringBuilder builder = new StringBuilder("0x");   // 16进制、Oracle里的Binary没有测试。
                foreach (Byte b in columnValue as Byte[])
                {
                    string tmp = Convert.ToString(b, 16);
                    if (tmp.Length < 2)
                        tmp = "0" + tmp;
                    builder.Append(tmp);
                }
                return builder.ToString();
            }
            else
            {
                return columnValue.ToString();
            }
        }

        private DataTable getTableSchema(String tableName, String connectionString, String connectionType)
        {
            IDbConnection conn = CreateConnection(connectionType, connectionString);
            String strSql = "select * from " + tableName;
            if (conn.State == ConnectionState.Closed) conn.Open();
            IDbCommand cmd = CreateCommand(this.cbConnType.Text, conn, strSql);
            IDataReader idr = cmd.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo);
            DataTable dt = idr.GetSchemaTable();
            return dt;
        }

        private void Login(String DB, String Solution)
        {
            OptionMessage = getOption();
            bool freg = Register(false, OptionMessage[0]);

            CliUtils.fLoginUser = OptionMessage[1];
            CliUtils.fLoginPassword = OptionMessage[2];
            CliUtils.fLoginDB = DB;
            CliUtils.fCurrentProject = Solution;
            if (CliUtils.fLoginUser.ToLower().Contains("'"))
            {
                String message = "UserID can not be null!";
                MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CliUtils.fLoginUser = "";
            }
            String sParam = CliUtils.fLoginUser + ':' + CliUtils.fLoginPassword + ':' + CliUtils.fLoginDB + ':' + "0";
        Label2:
            object[] myRet = CliUtils.CallMethod("GLModule", "CheckUser", new object[] { (object)sParam });
            if (myRet[1].ToString() == "1")
            {
                String message = "Password is error. Please check it again!";
                MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CliUtils.fLoginUser = "";
            }
            else if (myRet[1].ToString() == "3")
            {
                string message = "UserID:" + CliUtils.fLoginUser + " is not found!";
                MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CliUtils.fLoginUser = "";
            }
            else if (myRet[1].ToString() == "2")
            {
                String message = "UserID:" + CliUtils.fLoginUser + " has already loged!"; ;
                if (MessageBox.Show(String.Format(message, CliUtils.fLoginUser), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    sParam = CliUtils.fLoginUser + ':' + CliUtils.fLoginPassword + ':' + CliUtils.fLoginDB + ':' + "1";
                    goto Label2;
                }
                else
                {
                    CliUtils.fLoginUser = "";
                }
            }
            else//suceed to login...
            {
                CliUtils.fUserName = myRet[2].ToString();
                CliUtils.fLoginUser = myRet[3].ToString();
                myRet = CliUtils.CallMethod("GLModule", "GetUserGroup", new object[] { CliUtils.fLoginUser });
                if (myRet != null && (int)myRet[0] == 0)
                {
                    CliUtils.fGroupID = myRet[1].ToString();
                }
                SaveToClientXML(CliUtils.fLoginUser, CliUtils.fLoginDB, CliUtils.fCurrentProject);
            }
        }


        //imports SetLocalTime function from kernel32.dll 
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern int SetLocalTime(ref SystemTime lpSystemTime); 

        private void SetTime(String ServerDate, String ServerTime)
        {
            SystemTime systNew = new SystemTime();
            DateTime date = Convert.ToDateTime(ServerDate);
            DateTime time = Convert.ToDateTime(ServerTime);

            // 设置属性 
            systNew.wDay = Convert.ToInt16(date.Day);
            systNew.wMonth = Convert.ToInt16(date.Month);
            systNew.wYear = Convert.ToInt16(date.Year);
            systNew.wHour = Convert.ToInt16(time.Hour);
            systNew.wMinute = Convert.ToInt16(time.Minute);
            systNew.wSecond = Convert.ToInt16(time.Second); 

            SetLocalTime(ref systNew); 

        }

        private void LogOut()
        {
            CliUtils.CallMethod("GLModule", "LogOut", new object[] { (object)(CliUtils.fLoginUser) });
        }

        private void SaveToClientXML(string sLoginUser, string sLoginDB, string sCurrentProject)
        {
            String sfile = Application.StartupPath + "\\EEPNetClient.xml";
            string sUser = sLoginUser;
            string sDB = sLoginDB;
            string sSol = sCurrentProject;
            string stemp = "";
            XmlDocument xml = new XmlDocument();
            if (File.Exists(sfile))
            {
                xml.Load(sfile);
                XmlNode el = xml.DocumentElement;
                foreach (XmlNode xNode in el.ChildNodes)
                {

                    if (xNode.Name.ToUpper().Equals("USER"))
                    {
                        stemp = xNode.InnerText.Trim();
                        string[] ss = stemp.Split(new char[] { ',' });
                        foreach (string s in ss)
                        {
                            if (!s.Equals(sLoginUser))
                                sUser = sUser + "," + s;
                        }
                    }
                    else if (xNode.Name.ToUpper().Equals("DATABASE"))
                    {
                        stemp = xNode.InnerText.Trim();
                        string[] ss = stemp.Split(new char[] { ',' });
                        foreach (string s in ss)
                        {
                            if (!s.Equals(sLoginDB))
                                sDB = sDB + "," + s;
                        }
                    }
                    else if (xNode.Name.ToUpper().Equals("SOLUTION"))
                    {
                        stemp = xNode.InnerText.Trim();
                        string[] ss = stemp.Split(new char[] { ',' });
                        foreach (string s in ss)
                        {
                            if (!s.Equals(sCurrentProject))
                                sSol = sSol + "," + s;
                        }
                    }
                }

                File.Delete(sfile);
            }
            else
            {
                sUser = sLoginUser; sDB = sLoginDB; sSol = sCurrentProject;
            }

            FileStream aFileStream = new FileStream(sfile, FileMode.Create);
            try
            {
                XmlTextWriter w = new XmlTextWriter(aFileStream, new System.Text.ASCIIEncoding());
                w.Formatting = Formatting.Indented;
                w.WriteStartElement("LoginInfo");

                w.WriteStartElement("User");
                w.WriteValue(sUser);
                w.WriteEndElement();

                w.WriteStartElement("DataBase");
                w.WriteValue(sDB);
                w.WriteEndElement();

                w.WriteStartElement("Solution");
                w.WriteValue(sSol);
                w.WriteEndElement();

                w.WriteEndElement();
                w.Close();
            }
            finally
            {
                aFileStream.Close();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            OptionMessage = getOption();
            if (OptionMessage[6] != "")
            {
                String[] Time = OptionMessage[6].Split(';');
                bool flag = false;
                DateTime temp;
                foreach (String str in Time)
                {
                    temp = Convert.ToDateTime(str);
                    if (temp.ToShortTimeString() == DateTime.Now.ToShortTimeString()) flag = true;
                }
                if (!flag) return;
            }

            string s = Application.StartupPath + "\\EEPClientDBSocket.xml";
            if (File.Exists(s))
            {
                XmlDocument DBXML = new XmlDocument();
                FileStream aFileStream = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.None);
                DBXML.Load(aFileStream);
                XmlNode aNode = DBXML.DocumentElement.FirstChild;
                try
                {
                    while (aNode != null)
                    {
                        if (Convert.ToBoolean(aNode.Attributes["isActive"].Value))
                        {
                            Excute(aNode.Attributes["SocketName"].Value,
                                    aNode.Attributes["WhereString"].Value,
                                    aNode.Attributes["ConnString"].Value,
                                    aNode.Attributes["ConnType"].Value,
                                    aNode.Attributes["LocalTable"].Value,
                                    aNode.Attributes["ProviderName"].Value,
                                    aNode.Attributes["Field"].Value,
                                    aNode.Attributes["OperateMode"].Value,
                                    aNode.Attributes["Mode"].Value,
                                    aNode.Attributes["DataBase"].Value,
                                    aNode.Attributes["Solution"].Value);
                        }
                        aNode = aNode.NextSibling;
                    }
                }
                finally
                {
                    aFileStream.Close();
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DoDelete();
        }

        private void SetMonitor(String socketName, String action, String providerName, String tableName, String startTime, String endTime)
        {
            String s = Application.StartupPath + "\\EEPClientDBSocketMonitor.xml";
            XmlDocument DBXML = new XmlDocument();
            FileStream aFileStream;
            if (!File.Exists(s))
            {
                try
                {
                    aFileStream = new FileStream(s, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
                    try
                    {
                        XmlTextWriter w = new XmlTextWriter(aFileStream, new System.Text.ASCIIEncoding());
                        w.Formatting = Formatting.Indented;
                        w.WriteStartElement("InfolightEEPClientDBSocketMonitor");
                        w.WriteEndElement();
                        w.Close();
                    }
                    finally
                    {
                        aFileStream.Close();
                    }
                }
                catch (Exception er) { string str = er.Message; }
            }

            try
            {
                aFileStream = new FileStream(s, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                try
                {
                    DBXML.Load(aFileStream);
                    XmlNode aNode = null;

                    for (int j = DBXML.DocumentElement.ChildNodes.Count - 1; j >= 0; j--)
                        if (DBXML.DocumentElement.ChildNodes[j].Attributes["socketName"].Value.Trim().ToUpper().Equals(socketName.ToUpper()))
                        {
                            aNode = DBXML.DocumentElement.ChildNodes[j];
                            break;
                        }

                    if (aNode == null)
                    {
                        XmlElement elem = DBXML.CreateElement("String");
                        XmlAttribute attr = DBXML.CreateAttribute("socketName");
                        attr.Value = socketName;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("action");
                        attr.Value = action;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("providerName");
                        attr.Value = providerName;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("tableName");
                        attr.Value = tableName;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("startTime");
                        attr.Value = startTime;
                        elem.Attributes.Append(attr);

                        attr = DBXML.CreateAttribute("endTime");
                        attr.Value = endTime;
                        elem.Attributes.Append(attr);
                        DBXML.DocumentElement.AppendChild(elem);
                    }
                    else
                    {
                        aNode.Attributes["socketName"].InnerText = socketName;
                        aNode.Attributes["action"].InnerText = action;
                        aNode.Attributes["providerName"].InnerText = providerName;
                        aNode.Attributes["tableName"].InnerText = tableName;
                        aNode.Attributes["startTime"].InnerText = startTime;
                        aNode.Attributes["endTime"].InnerText = endTime;
                    }
                }
                finally
                {
                    aFileStream.Close();
                }
                DBXML.Save(s);
            }
            catch (Exception er) { string str = er.Message; }
        }

        private void TSMainMonitor_Click(object sender, EventArgs e)
        {
            frmMonitor fm = new frmMonitor();
            fm.ShowDialog();
        }

        private void TSMainExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void btnField_Click(object sender, EventArgs e)
        {
            List<String> fields = GetKeyFields();
            String[] selected = this.tbField.Text.Split(';');
            frmFields ff = new frmFields(fields, selected);
            ff.ShowDialog();
            this.tbField.Text = ff.values;
        }
    }

    //struct for date/time apis 
    public struct SystemTime
    {
        public short wYear;
        public short wMonth;
        public short wDayOfWeek;
        public short wDay;
        public short wHour;
        public short wMinute;
        public short wSecond;
        public short wMilliseconds;
    } 
}